package com.netted.operationassistant.activity;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.android.volley.VolleyError;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.mylhyl.superdialog.SuperDialog;
import com.netted.operationassistant.R;
import com.netted.operationassistant.constant.Constant;
import com.netted.operationassistant.entity.Port;
import com.netted.operationassistant.fragment.MyCodeUtils;
import com.netted.operationassistant.http.HttpRequest;
import com.netted.operationassistant.utils.QrCodeUtils;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.util.HashMap;
import java.util.Map;
public class ReturnDeviceActivity extends BaseActivity  {

    ProgressDialog loadingDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_return_device);

    }




    public void returnSuccess(String catbinetId,String port ){
        Map<String,String> params = new HashMap<>();
        params.put("catbinetId",catbinetId);
        params.put("port",port);
        loadingDialog = ProgressDialog.show(ReturnDeviceActivity.this,"提示", "读取中...", true, false);
        request.post(Constant.HOST+"/ws/opt/returnSuccess",params, "post", new HttpRequest.Callback() {
            @Override
            public void onSuccess(String response) {
                try{
                    loadingDialog.dismiss();
                    if (!StringUtils.isEmpty(response)){
                        JSONObject json = JSONObject.parseObject(response);
                        String data = json.getString("data");
                        if ("success".equals(json.getString("flag")) && !StringUtils.isEmpty(data)){
                            showDialog("提示", json.getString("message"), new SuperDialog.OnClickPositiveListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent = new Intent(ReturnDeviceActivity.this,MenuActivity.class);
                                    startActivity(intent);
                                    ReturnDeviceActivity.this.finish();
                                    return;
                                }
                            });
                        }else{
                            showDialog("提示",json.getString("message"),new SuperDialog.OnClickPositiveListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent = new Intent(ReturnDeviceActivity.this,MenuActivity.class);
                                    startActivity(intent);
                                    ReturnDeviceActivity.this.finish();
                                    return;
                                }
                            });
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    showDialog("提示","网络异常,请联系管理员",null);
                }
            }

            @Override
            public void onError(VolleyError error) {
                loadingDialog.dismiss();
                showDialog("t",error.toString(),null);
            }

        });
    }


    /**
     * 归还平板http请求,服务器判断是否有报修
     * @param catbinetId
     * @param deviceId
     */
    public void returnDevice(String catbinetId,String deviceId){
        final Map<String,String> params = new HashMap<>();
        params.put("catbinetId",catbinetId);
        params.put("deviceId",deviceId);
        loadingDialog = ProgressDialog.show(ReturnDeviceActivity.this,"提示", "读取中...", true, false);
        request.post(Constant.HOST+"/ws/opt/returnDevice",params, "post", new HttpRequest.Callback() {
            @Override
            public void onSuccess(String response) {
                try{
                    loadingDialog.dismiss();
                    if (!StringUtils.isEmpty(response)){
                        JSONObject json = JSONObject.parseObject(response);
                        String data = json.getString("data");
                        if ("success".equals(json.getString("flag")) && !StringUtils.isEmpty(data)){
                            JSONObject dataJson = JSONObject.parseObject(data);
                            String portStr = dataJson.getString("port");
                            String token = dataJson.getString("token");
                            Port p = getPortStatus(portStr);
                            if (p == null || p.getIsHas().equals("Y")){
                                showDialog("提示", "仓内已有平板,不可归还平板", new SuperDialog.OnClickPositiveListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Intent intent = new Intent(ReturnDeviceActivity.this,MenuActivity.class);
                                        startActivity(intent);
                                        ReturnDeviceActivity.this.finish();
                                        return;
                                    }
                                });
                                return;
                            }
                            playSound(ReturnDeviceActivity.this,R.raw.s2);

                            openPort(portStr);

                            Thread.sleep(1000);
                            Intent intent = new Intent(ReturnDeviceActivity.this,ReturnTipsActivity.class);
                            intent.putExtra("portStr",portStr);
                            intent.putExtra("from","ReturnDeviceActivity");                                     startActivity(intent);
                            startActivity(intent);
                            ReturnDeviceActivity.this.finish();
                        }else{

                            if ("错误的取机码".equals(json.getString("message"))){
                                playSound(ReturnDeviceActivity.this,R.raw.s7);
                            }

                            showDialog("提示",json.getString("message"),null);
                            return;
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    showDialog("提示","网络异常,请联系管理员",null);
                }
            }

            @Override
            public void onError(VolleyError error) {
                loadingDialog.dismiss();
                showDialog("t",error.toString(),null);
            }

        });
    }

    @Override
    protected void onRestart() {
        super.onRestart();

    }


    @Override
    protected void onResume() {
        super.onResume();
        String from = getIntent().getStringExtra("from");
        if ("RetrunTipsActivity".equals(from)){
            String portStr = getIntent().getStringExtra("portStr");
            String catbinetId = sharedPreferencesHelper.getSharedPreference(Constant.XML_CATBINET_ID,"")+"";
            returnSuccess( catbinetId, portStr );
        }else if("MenuActivity".equals(from)){
            qrcode(null);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    public void qrcode(View view){
        Intent intent = new Intent(this,QrCodeActivity.class);
        intent.putExtra("from","returnDeviceActivity");
        startActivityForResult(intent, MyCodeUtils.RESULT_SUCCESS);
//        this.finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CodeUtils.RESULT_SUCCESS) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == MyCodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(MyCodeUtils.RESULT_STRING);
                    String catbinetId = sharedPreferencesHelper.getSharedPreference(Constant.XML_CATBINET_ID,"")+"";
                    if (result.indexOf('[') > -1 && result.indexOf(']') > -1){
                        String deviceId = result.substring(result.indexOf('[') + 1,result.indexOf(']'));
                        returnDevice(catbinetId,deviceId);
                    }else{
                        showDialog("提示", "无效的二维码", new SuperDialog.OnClickPositiveListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(ReturnDeviceActivity.this,MenuActivity.class);
                                startActivity(intent);
                                ReturnDeviceActivity.this.finish();
                            }
                        });
                    }



                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == MyCodeUtils.RESULT_FAILED) {
                    Toast.makeText(ReturnDeviceActivity.this, "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    public void gotoBXHJ(View view){
        Intent intent = new Intent(this,BXHJActivity.class);
        startActivity(intent);
        this.finish();
    }



    public void exitActivity(View view){
        Intent intent = new Intent(this,MenuActivity.class);
        startActivity(intent);
        ActivityUtils.finishActivity(ReturnDeviceActivity.class);
    }



    @Override
    public void onBackPressed() {
        Intent intent = new Intent(this,MenuActivity.class);
        startActivity(intent);
        ActivityUtils.finishActivity(ReturnDeviceActivity.class);
    }




}
